﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using WeChatHelper;
using WX.Model;
using WeChatService.Models;
using WeChatService.WeChatHelper;

namespace WeChatService
{
    public partial class wx : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //微信服务器一直把用户发过来的消息，post过来
                if (Request.HttpMethod == "POST")
                {
                    var reader = XmlReader.Create(Request.InputStream);
                    var doc = XDocument.Load(reader);
                    MyLog.Log(doc.ToString());
                    var xml = doc.Element("xml");
                    var msg = new MiddleMessage(xml);
                    //把inputstream转换成xelement后，直接交给WebMessageRole来处理
                    var responseMessage = new WebMessageRole()
                        .MessageRole(msg)
                        .HandlerRequestMessage(msg);

                    if (responseMessage != null)
                    {
                        MyLog.Log(responseMessage.Serializable());
                        Response.Write(responseMessage.Serializable());
                    }
                }
                else if (Request.HttpMethod == "GET") 
                {
                    Auth();
                    //Response.Write(Request["echostr"].ToString());
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        /// <summary>
        /// 验证并响应服务器的数据
        /// </summary>
        private void Auth()
        {
            string token = Common.token;
            
            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["signature"];
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];

            if (CheckSignature(token, signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoString))
                {
                    HttpContext.Current.Response.Write(echoString);
                    HttpContext.Current.Response.End();
                }
            }
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        private bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };

            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);

            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}